package com.java.jwt.filter.utils.filter;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.java.jwt.filter.utils.config.UserGrantedAuthority;
import com.java.jwt.filter.utils.utils.RequestHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 陈烽
 */
@Slf4j
public class JwtAuthenticationFilters extends BasicAuthenticationFilter {

    //    @Value("${jwt.secret}")
    private String jwtSecret = "test_key";
    private final String BEARER_PREFIX = "Bearer ";
    private final String BEARER_PREFIX1 = "\tBearer ";

    //    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, String jwtSecret) {
//        super(authenticationManager);
//        this.jwtSecret = jwtSecret;
//    }
    public JwtAuthenticationFilters(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        log.info("过滤器启动");
        String authorization = request.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith(BEARER_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(authorization);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(String authorization) {
        if (authorization != null) {
            try {
                Claims jwt = Jwts.parser()
                        .setSigningKey(jwtSecret.getBytes(StandardCharsets.UTF_8))
                        .parseClaimsJws(authorization.replace(BEARER_PREFIX1, ""))
                        .getBody();
                Object enhance = jwt.get("enhance");
                Object username = jwt.get("username");
                Object password = jwt.get("password");
                Object authorities1 = jwt.get("Authorities");
                Collection<GrantedAuthority> authorities = new ArrayList<>();
//                GrantedAuthority grantedAuthority = new UserGrantedAuthority(authorities1.toString());
                GrantedAuthority grantedAuthority = new UserGrantedAuthority("cf:admin");
                //加载到全局变量
                authorities.add(grantedAuthority);
                RequestHolder.set("enhance", enhance.toString());
                RequestHolder.set("username", username);
                RequestHolder.set("password", password);
                RequestHolder.set("Authorities", authorities1);
                log.info("过滤器搭配成功");
//                log.info(enhance.toString());
//                log.info(principal.toString());
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
//                return new UsernamePasswordAuthenticationToken(null, null, null);
            } catch (JWTVerificationException exception) {
                return null;
            }
        }
        return null;
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
        RequestHolder.remove();
        super.destroy();
    }
}
